/**
 * @file main.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2024-01-23
 *
 * @copyright Copyright (c) 2024
 *
*/
#include <FreeRTOS.h>
#include "task.h"
#include "queue.h"
#include "board.h"
#include "bluetooth.h"
#include "btble_lib_api.h"
#include "bl616_glb.h"
#include "rfparam_adapter.h"
#include "bflb_mtd.h"
#include "easyflash.h"
#include "wifi_event.h"
#include "log.h"
#include "aiio_os_port.h"
#include "homeAssistantMQTT.h"

#define DBG_TAG "MAIN"

void ha_event_cb(ha_event_t event, homeAssisatnt_device_t* ha_dev)
{
    switch (event)
    {
        case HA_EVENT_MQTT_CONNECED:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_CONNECED");
            //一定要加static
            static ha_sw_entity_t entity_sw1 = {
                 .name = "开关1",
                 .icon = "mdi:power",
                 .unique_id = "switch1",
            };
            homeAssistant_device_add_entity(CONFIG_HA_ENTITY_SWITCH, &entity_sw1);
            homeAssistant_device_send_status(HOMEASSISTANT_STATUS_ONLINE);
            homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, &entity_sw1, 0);
            break;
        case HA_EVENT_MQTT_DISCONNECT:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_DISCONNECT");

            break;
        case HA_EVENT_MQTT_COMMAND_SWITCH:
            LOG_I("<<<<<<<<<<  HA_EVENT_MQTT_COMMAND_SWITCH");
            // LOG_I("switch addr =%p", ha_dev->entity_switch->command_switch);
            LOG_I(" switch %s is %s", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"true":"flase");
            int ret = homeAssistant_device_send_entity_state(CONFIG_HA_ENTITY_SWITCH, ha_dev->entity_switch->command_switch, ha_dev->entity_switch->command_switch->switch_state);
            if (ret!=-1)LOG_I("%s send entity suceess,state=%s", ha_dev->entity_switch->command_switch->name, ha_dev->entity_switch->command_switch->switch_state?"true":"flase");
            break;
        default:
            break;
    }
}

int main(void)
{

    board_init();
    bflb_mtd_init();
    easyflash_init();
    // aiio_log_init();

    if (0 != rfparam_init(0, NULL, 0)) {
        LOG_E("PHY RF init failed!\r\n");
        return 0;
    }

    staWiFiInit();
    // homeassistant_blufi_init();
    static homeAssisatnt_device_t ha_device;
    homeAssistant_device_init(&ha_device, ha_event_cb);
    vTaskStartScheduler();

    while (1) {
        LOG_F("HomeAssistant free heap size=%d", aiio_os_get_free_heap_size());
        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}
